
import '../lib/jquery.js'
import { $messageTip, $axios } from './util.js'

const axios = $axios()

let userInfo = sessionStorage.getItem('frontUserInfo')
if (!userInfo) {
  window.location.href = './index.html'
}

$(document).ready(function() {
  $('button').on('click', function () {
    updatePassword();
  });

  function updatePassword() {
    let user = sessionStorage.getItem('frontUserInfo');
    if (user) {
      user = JSON.parse(user);
    
      const requestData = JSON.stringify({
        id: user.id,
        oldPassword: $('.oldpassword').val(),
        newPassword: $('.newpassword').val(),
        rNewPassword: $('.rnewpassword').val()
      });
      axios.post('/users/rpwd', requestData, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        if (response.data) {
          const responseData = JSON.parse(response.data);

          if (responseData.code === 1) {
            $messageTip(responseData.message);
            sessionStorage.removeItem('frontUserInfo');
            sessionStorage.removeItem('frontToken');
            setTimeout(() => {
              window.location.href = './login.html';
            }, 1000);
          } else {
            $messageTip(responseData.message);
          }
        }
      }).catch(error => {
        console.log(error);
      });
    } else {
      window.location.href = './index.html';
    }
  }
});
